package controllers

import (
	//	"encoding/json"
	"errors"
	"gitee.com/lzqysoft/ilive/models"
	"strconv"
	"strings"

	"github.com/astaxie/beego"
	//	"fmt"
	"gitee.com/lzqysoft/ilive/libs"
	"time"
	//	"fmt"
	"os"
	"path"
)

// oprations for Dept
type DeptController struct {
	CommonController
}

func (c *DeptController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("GetOne", c.GetOne)
	c.Mapping("GetAll", c.GetAll)
	c.Mapping("Update", c.Update)
	c.Mapping("Delete", c.Delete)
	c.Mapping("UploadPhoto", c.UploadPhoto)
	c.Mapping("DeleteDepts", c.DeleteDepts)
	c.Mapping("AssignUserDept", c.AssignUserDept)

}

// @Title Post
// @Description create Dept
// @Param	body		body 	models.Dept	true		"body for Dept content"
// @Success 201 {int} models.Dept
// @Failure 403 body is empty
// @router / [post]
func (c *DeptController) Post() {
	user := c.user
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.(map[string]interface{})
	var v models.Dept
	v.Name, _ = sdata["Name"].(string)
	v.Remark, _ = sdata["Remark"].(string)
	vpid, _ := sdata["Pid"].(string)
	vstatus, _ := sdata["Status"].(string)
	v.Status, _ = strconv.ParseInt(vstatus, 10, 64)
	v.Pid, _ = strconv.ParseInt(vpid, 10, 64)
	v.Level = 1
	v.Seq = 100
	v.Creater = user.Name
	v.Ctime = time.Now()
	v.Updater = v.Creater
	v.Utime = v.Ctime
	v.Organization = user.Organization
	v.Isdelete = 0
	if did, err := models.AddDept(&v); err == nil {
		c.Dlog("添加了部门，id是：", did)
		c.RetSuccess(did)

	}
	c.RetError(ErrDatabase)
}

// @Title Get
// @Description get Dept by id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.Dept
// @Failure 403 :id is empty
// @router /:id [get]
func (c *DeptController) GetOne() {
	id, _ := c.GetInt64(":id")
	v, err := models.GetDeptById(id)
	if err != nil {
		c.RetError(ErrNoData)
	}
	c.RetSuccess(v)
}

// @Title Get All
// @Description get Dept
// @Param	query	query	string	false	"Filter. e.g. col1:v1,col2:v2 ..."
// @Param	fields	query	string	false	"Fields returned. e.g. col1,col2 ..."
// @Param	sortby	query	string	false	"Sorted-by fields. e.g. col1,col2 ..."
// @Param	order	query	string	false	"Order corresponding to each sortby field, if single value, apply to all sortby fields. e.g. desc,asc ..."
// @Param	limit	query	string	false	"Limit the size of result set. Must be an integer"
// @Param	offset	query	string	false	"Start position of result set. Must be an integer"
// @Success 200 {object} models.Dept
// @Failure 403
// @router / [get]
func (c *DeptController) GetAll() {
	user := c.user

	var fields []string
	var sortby []string
	var order []string
	var query map[string]string = make(map[string]string)
	var limit int64 = -1
	var offset int64 = 0
	query["Organization"] = strconv.FormatInt(user.Organization.Id, 10)
	// fields: col1,col2,entity.col3
	if v := c.GetString("fields"); v != "" {
		fields = strings.Split(v, ",")
	}
	// limit: 10 (default is 10)
	if v, err := c.GetInt64("limit"); err == nil {
		limit = v
	}
	// offset: 0 (default is 0)
	if v, err := c.GetInt64("offset"); err == nil {
		offset = v
	}
	// sortby: col1,col2
	if v := c.GetString("sortby"); v != "" {
		sortby = strings.Split(v, ",")
	}
	sortby = append(sortby, "Seq")
	// order: desc,asc
	if v := c.GetString("order"); v != "" {
		order = strings.Split(v, ",")
	}
	order = append(order, "asc")
	// query: k:v,k:v
	if v := c.GetString("query"); v != "" {
		for _, cond := range strings.Split(v, ",") {
			kv := strings.SplitN(cond, ":", 2)
			if len(kv) != 2 {
				c.Data["json"] = errors.New("Error: invalid query key/value pair")
				c.ServeJSON()
				return
			}
			k, v := kv[0], kv[1]
			query[k] = v
		}
	}

	l, err := models.GetAllDept(query, fields, sortby, order, offset, limit)
	if err != nil {
		c.RetError(ErrDatabase)
	}
	//	tree := make(map[string]interface{})
	//	treedata := make([]map[string]interface{}, 0)
	//	org, _ := models.GetOrganizationById(user.OrgId)
	//	tree["org_id"] = user.OrgId
	//	tree["id"] = user.OrgId
	//	tree["expand"] = true
	//	tree["title"] = org.Name
	//	tree["children"] = models.GetDeptTreeByParentIdAndOrgId(0, user.OrgId)
	//	treedata = append(treedata, tree)
	udtree, _ := models.GetUserDeptTree(user.Organization.Id)
	tabledata := make(map[string]interface{})
	tabledata["treedata"] = udtree
	tabledata["tabledata"] = l
	c.RetSuccess(tabledata)
}

// @Title Update
// @Description update the Dept
// @Param	id		path 	string	true		"The id you want to update"
// @Param	body		body 	models.Dept	true		"body for Dept content"
// @Success 200 {object} models.Dept
// @Failure 403 :id is not int
// @router /Update [post]
func (c *DeptController) Update() {
	user := c.user
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.(map[string]interface{})
	sid := sdata["Id"].(string)
	id, _ := strconv.ParseInt(sid, 10, 64)
	v, _ := models.GetDeptById(id)

	v.Name, _ = sdata["Name"].(string)
	v.Remark, _ = sdata["Remark"].(string)
	vpid, _ := sdata["Pid"].(string)
	vstatus, _ := sdata["Status"].(string)
	v.Status, _ = strconv.ParseInt(vstatus, 10, 64)
	v.Pid, _ = strconv.ParseInt(vpid, 10, 64)
	vseq, _ := sdata["Seq"].(string)

	v.Seq, _ = strconv.ParseInt(vseq, 10, 64)
	v.Updater = user.Name
	v.Utime = time.Now()

	if err := models.UpdateDeptById(v); err == nil {
		c.Dlog("修改了部门信息,部门id为：", id)
		c.RetSuccess(id)
	}
	c.RetError(ErrDatabase)
}

// @Title Delete
// @Description delete the Dept
// @Param	id		path 	string	true		"The id you want to delete"
// @Success 200 {string} delete success!
// @Failure 403 id is empty
// @router /Delete [post]
func (c *DeptController) Delete() {
	user := c.user
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.(map[string]interface{})
	sid := sdata["Id"].(string)
	id, err := strconv.ParseInt(sid, 10, 64)
	if err, rs := models.GetDeptByPid(id); err == nil && len(rs) > 0 {
		c.Data["json"] = "不允许删除有子部门的部门！"
		c.RetError(ErrPid)
	}
	if err := models.SoftDeleteDept(id, user.Name); err == nil {
		c.Dlog("删除了系统资源", id)
		c.RetSuccess(id)
	}
	c.RetError(ErrDatabase)
}

// @Title uploadPhoto
// @Description upload photo
// @Success 200 success
// @Failure 403
// @router /UploadPhoto [post]
func (c *DeptController) UploadPhoto() {
	id, err1 := c.GetInt64("id")
	ui := c.GetSession("userinfo")
	uf := c.GetSession("userprof")
	beego.Debug("session is 1111111111:", ui, uf)
	if err1 == nil {
		userPro, _ := models.GetUserprofById(id)
		f, h, err := c.GetFile("the_files")
		defer f.Close()
		if err != nil {
			c.Data["json"] = "error"
		} else {
			filename := libs.GetGuid()
			filetype := path.Ext(h.Filename)
			newName := filename + filetype
			os.Remove("." + userPro.Photo)
			userPro.Photo = "/imgs/" + newName
			models.UpdateUserprofById(userPro)
			v, _ := models.GetUserprofById(id)
			beego.Debug("session is 1111111111:", c.GetSession("userinfo"), c.GetSession("userprof"))
			//			c.DelSession("userprof")
			//			log.Debug("session is 22222222:", c.GetSession("userprof"))
			c.SetSession("userprof", v)
			beego.Debug("session is 3333333333:", c.GetSession("userprof"))

			c.SaveToFile("the_files", "imgs/"+newName)
			//			c.Dlog("上传了图片", 0)

			c.Data["json"] = userPro.Photo
		}
	} else {
		c.Data["json"] = "error"
	}
	c.ServeJSON()
}

// @Title DeleteDepts
// @Description DeleteDepts
// @Success 200
// @Failure 403
// @router /DeleteDepts [post]
func (c *DeptController) DeleteDepts() {
	user := c.user
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.([]interface{})
	for _, value := range sdata {
		eid := value.(string)
		id, _ := strconv.ParseInt(eid, 10, 64)
		err := models.SoftDeleteDept(id, user.Name)
		if err != nil {
			c.RetError(ErrDatabase)
		}
		c.Dlog("删除了部门，id为：", id)

	}
	c.RetSuccess(sdata)
}

// @Title AssignUserDept
// @Description 分配部门人员
// @Param	id		path 	string	true		"The id you want to delete"
// @Success 200 {string} delete success!
// @Failure 403 id is empty
// @router /AssignUserDept [post]
func (c *DeptController) AssignUserDept() {
	user := c.user
	rdata, err := c.AesDecode(c.GetString("tdata"))
	//	beego.Debug("rdatardatardata:", rdata)
	if err != nil {
		c.RetError(ErrToken)
	}
	err = models.DeleteUserDeptByOrg(user.Organization.Id)

	if err != nil {
		//		beego.Debug(err)
		c.RetError(ErrDatabase)
	}

	sdata, _ := rdata.([]interface{})
	for _, e := range sdata {
		ud := e.(map[string]interface{})
		if !ud["isParent"].(bool) && !ud["isHidden"].(bool) {
			userid, _ := ud["id"].(float64)
			deptid, _ := ud["pId"].(float64)
			_, err = models.AddUserDept(int64(deptid), int64(userid))
			//			beego.Debug("err is :", v, err)
			c.Dlog("添加了用户部门关系，用户id为:", int64(deptid))
		}
	}

	//	beego.Debug("sdatasdatasdatasdata:", sdata)
	//	beego.Debug("sdatasdatasdatasdata:", reflect.TypeOf(sdata))
	//	sid, _ := sdata["Roleid"].(float64)
	//	if err := models.DeleteUserDeptByOrg(user.OrgId); err == nil {
	//		c.Data["json"] = "OK"
	//	} else {
	//		c.Data["json"] = err.Error()
	//	}
	c.RetSuccess("ok")
}
